package com.huan.project;

import com.huan.Test3_TimeServer;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class Server {
    private static Logger logger = Logger.getLogger(Test3_TimeServer.class.getName());
    public static void main(String[] args) throws IOException {
        //1.创建ServerSocket 将端口配置在一个 xml/properties 文件中（实际开发中常用）
        int port = 0;
        ServerSocket serverSocket= null;
        Properties properties = new Properties();
        try (FileInputStream fis = new FileInputStream("src/main/resources/port.properties")) {
            properties.load(fis);
            port = Integer.parseInt(properties.getProperty("server.port"));
            // 创建 ServerSocket 并使用读取到的端口号
            serverSocket = new ServerSocket(port);
            System.out.println("Server started on port " + port);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            if (e instanceof BindException){
                //用错误日志记录端口被占用的信息
                logger.error("端口："+port+"已经被占用");
            }
            e.printStackTrace();
        }
        //用info级别记录 ServerSocket套接字创建成功的信息
        logger.info(serverSocket.getInetAddress().getHostName()+"启动了，监听端口号："+serverSocket.getLocalPort());
        //2.等待客户端连接
        while (true){
            //3.连接到客户端后，给客户发送规则说明
            /**
             1 查看当前时间
             2 精美句子
             3 哔哩哔哩热搜榜
             4 随机动漫画
             5 退出
             */
            logger.info("等待客户连接...");
            //获取客户套接字对象
            Socket s = serverSocket.accept();
            logger.info("获取了一个与客户端："+s.getRemoteSocketAddress()+"的连接");
            //以下步骤放在线程中处理
            //给客户发送规则说明
            //4.收到客户发送的请求，处理客户请求
            //6.处理获取的数据
            //7.将处理好的数据转发给客户
            //8.直至客户发送断开请求，断开连接
            Thread thread = new Thread(new ClientHandler(s));
            thread.start();


        }

    }
    /**
     * 发送向客户端发送数据
     */
    public static void sendMessage(BufferedWriter writer,String message) throws IOException {
        writer.write(message);
        writer.newLine();
        writer.flush();
    }
    private static class ClientHandler implements Runnable {
        private Socket s;

        public ClientHandler(Socket socket) {
            this.s = socket;
        }

        @Override
        public void run() {
            try (
                    Socket socket = this.s;//如果没有这个语句，则socket不能自动关闭
                    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    ){
                String rule = "欢迎使用本系统，如需以下功能请输入指定的序号（仅数字）\n" +
                        "1 查看当前时间\n" +
                        "2 精美句子\n" +
                        "3 哔哩哔哩热搜榜\n" +
                        "4 随机动漫画\n"+
                        "5 退出";
                writer.write(rule);
                writer.newLine();
                writer.flush();
                while (true && !socket.isClosed()) {
                    // 读取客户端发送的消息
                    String clientMessage = reader.readLine();
                    if (clientMessage == null) {
                        break; // 客户端断开连接
                    }
                    System.out.println("Received message from client: " + clientMessage);
                    // 根据收到的消息，处理业务逻辑
                    //5.然后发送请求到对应网站，获取数据
                    /**
                     1 查看当前时间
                     2 精美句子
                     3 哔哩哔哩热搜榜
                     4 随机动漫画
                     5 退出
                     */
                    switch (clientMessage){
                        case "1":
                            sendMessage(writer,getTime());break;
                        case "2":
                            sendMessage(writer,getSentence());break;
                        case "3":
                            sendMessage(writer,getBilibiliTopSearch());break;
                        case "4":
                            sendMessage(writer,getPictureUrl());break;
                        case "5":
                            System.out.println("客户端断开连接");
                            break;
                        default:
                            sendMessage(writer,"没有该指令,请重新输入~");break;
                    }
                }
                // 关闭连接
                socket.close();
                System.out.println("Connection closed");
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //1.查看当前时间
    public static String getTime(){
        DateFormat dateFormat = new SimpleDateFormat("yyyy年-MM月-dd日 HH:mm:ss");
        String time = dateFormat.format(new Date());
        return time;
    }

    //2.精美句子
    private static String getSentence() throws IOException, JSONException {
        String sentence = null;
        HttpURLConnection connection = null;
        URL url = new URL("https://v1.hitokoto.cn/");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String input;
        StringBuilder content = new StringBuilder();
        while ((input=in.readLine())!=null){
            content.append(input);
        }
        in.close();
        connection.disconnect();
        JSONObject jsonObj = new JSONObject(content.toString());;
        System.out.println(jsonObj.get("hitokoto").toString());
        return jsonObj.get("hitokoto").toString();
    }

    //3.哔哩哔哩热搜榜
    private static String getBilibiliTopSearch(){
        String hot = "";
        try {
            /**
             * 问题：
             * org.json.JSONException: Not a primitive array: class org.json.JSONArray
             */
            // 设置请求 URL
            URL url = new URL("https://tenapi.cn/v2/bilihot");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("GET");

            // 启用输入输出流
            connection.setDoOutput(true);

            JSONObject jsonObj = null;
            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                System.out.println("Response: " + response.toString());
                jsonObj = new JSONObject(response.toString());
            }
            //处理json数据，取到图片url
            JSONArray data = jsonObj.getJSONArray("data");

            for (int i = 1; i <= data.length(); i++) {
                JSONObject jsonObject = data.getJSONObject(i);
                String name = jsonObject.getString("name");
                String hUrl = jsonObject.getString("url");
                hot = hot+i+". "+name+":"+hUrl+"\n";
            }
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hot;
    }


    //4.随机动漫画,获取下载链接和尺寸信息，并下载至客户端本地
    private static String getPictureUrl(){
        String purl = "";
        try {
            // 设置请求 URL
            URL url = new URL("https://tenapi.cn/v2/acg");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");

            // 启用输入输出流
            connection.setDoOutput(true);

            // 设置请求参数
            String parameters = "format=json";
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = parameters.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            JSONObject jsonObj = null;
            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                System.out.println("Response: " + response.toString());
                jsonObj = new JSONObject(response.toString());
            }
            //处理json数据，取到图片url
            String data = jsonObj.get("data").toString();

            int start = data.indexOf("http");
            int end = data.indexOf(".jpg")+4;
            purl = data.substring(start,end).replace("\\/", "/");
            System.out.println(purl);
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return purl;
    }

}
